﻿using System;
using System.IO;

namespace DashFire
{
  public class FileCompress
  {
    public static void Compress(string inFile, string outFile)
    {
      SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder();
      FileStream input = new FileStream(inFile, FileMode.Open);
      FileStream output = new FileStream(outFile, FileMode.Create);

      // Write the encoder properties
      coder.WriteCoderProperties(output);

      // Write the decompressed file size.
      output.Write(BitConverter.GetBytes(input.Length), 0, 8);

      // Encode the file.
      coder.Code(input, output, input.Length, -1, null);
      output.Flush();
      output.Close();
      input.Close();
    }

    public static string Decompress(string inFile, string outFile)
    {
      FileStream input = null;
      FileStream output = null;
      try
      {
        input = new FileStream(inFile, FileMode.Open);
        output = new FileStream(outFile, FileMode.Create);
        SevenZip.Compression.LZMA.Decoder coder = new SevenZip.Compression.LZMA.Decoder();
        // Read the decoder properties
        byte[] properties = new byte[5];
        input.Read(properties, 0, 5);

        // Read in the decompress file size.
        byte[] fileLengthBytes = new byte[8];
        input.Read(fileLengthBytes, 0, 8);
        long fileLength = BitConverter.ToInt64(fileLengthBytes, 0);

        // Decompress the file.
        coder.SetDecoderProperties(properties);
        coder.Code(input, output, input.Length, fileLength, null);
        output.Flush();
      }
      catch(Exception e)
      {
        return string.Format("Decompress Error ({0},{1}) reason : {2}, {3}",
          inFile, outFile, e.Message, e.StackTrace);
      }

      output.Close();
      input.Close();

      return string.Empty;
    }

    public static void Decompress(byte[] bytes, string outFile)
    {
      SevenZip.Compression.LZMA.Decoder coder = new SevenZip.Compression.LZMA.Decoder();
      Stream input = new MemoryStream(bytes);
      FileStream output = new FileStream(outFile, FileMode.Create);

      // Read the decoder properties
      byte[] properties = new byte[5];
      input.Read(properties, 0, 5);

      // Read in the decompress file size.
      byte[] fileLengthBytes = new byte[8];
      input.Read(fileLengthBytes, 0, 8);
      long fileLength = BitConverter.ToInt64(fileLengthBytes, 0);

      // Decompress the file.
      coder.SetDecoderProperties(properties);
      coder.Code(input, output, input.Length, fileLength, null);
      output.Flush();
      output.Close();
      input.Close();
    }
  }
}
